<?php

namespace App\Http\Controllers\Family;

use App\Models\Category;
use App\Models\Child;
use App\Models\History;
use App\Models\Game;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TrainingController extends BaseController
{
    /**
     * 每个孩子的训练记录
     *
     * @Date 2020/7/29 上午9:50
     * @param $child_id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function index($child_id, Request $request)
    {
        $this->validate($request, [
            'grade_id' => 'sometimes|exists:grades,id',
            'category_id' => 'sometimes|exists:categories,id',
        ], [], [
            'category_id' => __("category"),
            'grade_id' => __("grade"),
        ]);

        $data = $request->only(['grade_id', 'category_id']);
        $categories = Category::all();

        $child = Child::find($child_id);
        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if (!$this->allow('family', $child)) {
            return back()->with('error', __('Sorry, you are not authorized to access this page.'))->withInput();
        }
        $list = History::where('child_id', $child_id)
            ->when(isset($data['grade_id']), function ($query) use ($data){
                $query->where("grade_id", $data['grade_id']);
            })
            ->when(isset($data['category_id']), function ($query) use ($data) {
                $query->where("category_id", $data['category_id']);
            })
            ->orderBy("id", "desc")
            ->paginate(config('site.other.paginate'));

        $query['grade_id'] =  $data['grade_id'];

        isset($data['category_id']) && $query['category_id'] = $data['category_id'];

        $list = $list->appends($query);

        return familyView('training.index', compact('list', 'child', 'categories', 'data'));
    }

    public function ajaxdata($child_id, Request $request)
    {

        $this->validate($request, [
            'grade_id' => 'sometimes|exists:grades,id',
            'category_id' => 'sometimes|exists:categories,id',
        ], [], [
            'category_id' => __("category"),
            'grade_id' => __("grade"),
        ]);

        $data = $request->only(['grade_id', 'category_id']);

        $child = Child::find($child_id);

        if (empty($child)) {
            return response()->json(['status' => 404, 'data' => []]);
        }

        if (!$this->allow('family', $child)) {
            return response()->json(['status' => 405, 'data' => []]);
        }

        $history = History::where('child_id', $child_id)
            ->when(isset($data['grade_id']), function ($query) use ($data) {
                $query->where("grade_id", $data['grade_id']);
            })
            ->when(isset($data['category_id']), function ($query) use ($data) {
                $query->where("category_id", $data['category_id']);
            })
            ->selectRaw('result, grade_id, category_id, game_id, count(id) as num')
            //->with('game')
            ->groupBy('result', 'grade_id', 'game_id', 'category_id', 'game_id')
            ->orderBy('num', 'desc')
            ->get();

        $s = [];
        foreach ($history as $t) {
            $s[$t->game_id][$t->result] = $t->num;
        }

        $games = Game::when(isset($data['grade_id']), function ($query) use ($data){
            $query->where("grade_id", $data['grade_id']);
        })
            ->when(isset($data['category_id']), function ($query)  use ($data){
                $query->where("category_id", $data['category_id']);
            })->get();

        $result = ['labels'=>[], 'successed'=>[], 'failed'=>[]];

        foreach ($games as $v) {
            $result['labels'][] = $v->name;

            if (isset($s[$v->id]) && isset($s[$v->id][1])){
                $result['successed'][] = $s[$v->id][1];
            }else{
                $result['successed'][] = 0;
            }

            if (isset($s[$v->id]) && isset($s[$v->id][0])){
                $result['failed'][] = $s[$v->id][0];
            }else{
                $result['failed'][] = 0;
            }
        }


        if (count($result) == 0) {
            return response()->json(['status' => 400, 'data' => []]);
        }

        return response()->json(['status' => 200, 'data' => $result]);
    }

    public function view($id)
    {
        $training = History::find($id);
        if (empty($training)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if (!$this->allow("family", $training->child)) {
            return back()->with('error', __("Sorry, you are not authorized to access this page."));
        }

        return familyView('training.view', compact('training'));
    }

    public function historyByGame($child_id, Request $request){

        $child = Child::find($child_id);

        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if (!$this->allow('family', $child)) {
            return back()->with('error', __('Sorry, you are not authorized to access this page.'))->withInput();
        }

        $game = Game::find($request->input("game_id"));

        if (empty($game)){
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        $list = History::where("child_id", $child_id)
            ->where("game_id", $request->input("game_id"))
            ->orderBy("id", "desc")->paginate(config('site.other.paginate'));

        return familyView('training.historybygame', compact('list', 'child', 'game'));
    }

    public function ajaxgamedata($child_id, Request $request)
    {
        $data = $request->only(['game_id']);

        $child = Child::find($child_id);

        if (empty($child)) {
            return response()->json(['status' => 404, 'data' => []]);
        }

        if (!$this->allow('family', $child)) {
            return response()->json(['status' => 405, 'data' => []]);
        }

        $game = Game::find($data["game_id"]);
        if (empty($game)){
            return response()->json(['status' => 405, 'data' => []]);
        }

        $history = History::where('child_id', $child_id)->where("game_id", $data["game_id"])->orderBy("id", "desc")->get();

        if (count($history) == 0) {
            return response()->json(['status' => 400, 'data' => []]);
        }

        $result = ['labels'=>[], 'y'=>[]];

        foreach ($history as $v){
            $result["labels"][] = $v->start_time;
            $result['y'][] = $v->result == 1 ? $v->getOriginal("use_time") : 0 - $v->getOriginal("use_time");
        }

        return response()->json(['status' => 200, 'data' => $result]);
    }

}
